const https = require('https')
const http = require('http')

const API_BASE_URL = 'http://localhost:5000/api'

// 测试配置
const TEST_CONFIG = {
  userId: 'test_user_001',
  timeout: 10000,
  retries: 3
}

// 测试用例数据
const TEST_DATA = {
  smartParse: [
    '明天下午3点给老王打电话汇报工作',
    '这周完成项目文档，优先级高',
    '下周一开会讨论新功能，准备演示材料',
    '今天必须完成的紧急任务',
    '学习React框架，计划2周内掌握基础'
  ],
  decomposeTask: [
    { title: '完成季度报告', description: '需要整理销售数据、分析市场趋势、制定下季度计划' },
    { title: '组织团队建设活动', description: '安排活动场地、准备游戏道具、邀请团队成员' },
    { title: '升级系统架构', description: '评估现有系统、设计新架构、制定迁移计划' }
  ],
  search: [
    '高优先级任务',
    '这周要完成的',
    '还没开始的工作',
    '上周开会提到的',
    '我拖延了很久的事情'
  ],
  personalizedSuggestions: [
    { userId: 'test_user_001', context: '工作繁忙，需要提高效率' },
    { userId: 'test_user_002', context: '学习新技能，时间管理' },
    { userId: 'test_user_003', context: '项目管理，团队协作' }
  ]
}

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m'
}

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`)
}

function logSuccess(message) {
  log(`✅ ${message}`, 'green')
}

function logError(message) {
  log(`❌ ${message}`, 'red')
}

function logWarning(message) {
  log(`⚠️ ${message}`, 'yellow')
}

function logInfo(message) {
  log(`ℹ️ ${message}`, 'blue')
}

function logHeader(message) {
  log(`\n${colors.bright}${colors.cyan}${'='.repeat(50)}${colors.reset}`)
  log(`${colors.bright}${colors.cyan}${message}${colors.reset}`)
  log(`${colors.bright}${colors.cyan}${'='.repeat(50)}${colors.reset}`)
}

// 通用API请求函数
async function apiRequest(endpoint, options = {}) {
  const url = `${API_BASE_URL}${endpoint}`
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  }

  return new Promise((resolve, reject) => {
    const urlObj = new URL(url)
    const isHttps = urlObj.protocol === 'https:'
    const client = isHttps ? https : http
    
    const requestOptions = {
      hostname: urlObj.hostname,
      port: urlObj.port || (isHttps ? 443 : 80),
      path: urlObj.pathname + urlObj.search,
      method: defaultOptions.method || 'GET',
      headers: defaultOptions.headers
    }

    if (defaultOptions.body) {
      requestOptions.headers['Content-Length'] = Buffer.byteLength(defaultOptions.body)
    }

    const req = client.request(requestOptions, (res) => {
      let data = ''
      
      res.on('data', (chunk) => {
        data += chunk
      })
      
      res.on('end', () => {
        try {
          if (res.statusCode >= 200 && res.statusCode < 300) {
            const jsonData = JSON.parse(data)
            resolve(jsonData)
          } else {
            reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`))
          }
        } catch (error) {
          reject(new Error(`JSON解析失败: ${error.message}`))
        }
      })
    })

    req.on('error', (error) => {
      reject(new Error(`请求失败: ${error.message}`))
    })

    if (defaultOptions.body) {
      req.write(defaultOptions.body)
    }
    
    req.end()
  })
}

// 测试智能解析接口
async function testSmartParse() {
  logHeader('测试智能解析接口 (smart-parse)')
  
  for (let i = 0; i < TEST_DATA.smartParse.length; i++) {
    const text = TEST_DATA.smartParse[i]
    logInfo(`测试用例 ${i + 1}: "${text}"`)
    
    try {
      const result = await apiRequest('/ai/smart-parse', {
        method: 'POST',
        body: JSON.stringify({ text })
      })
      
      if (result.success) {
        logSuccess(`解析成功: ${result.message}`)
        if (result.result) {
          log(`   - 标题: ${result.result.title || 'N/A'}`)
          log(`   - 截止日期: ${result.result.dueDate || 'N/A'}`)
          log(`   - 优先级: ${result.result.priority || 'N/A'}`)
          log(`   - 分类: ${result.result.category || 'N/A'}`)
          log(`   - 标签: ${result.result.tags ? result.result.tags.join(', ') : 'N/A'}`)
          log(`   - 备注: ${result.result.notes || 'N/A'}`)
        }
      } else {
        logWarning(`解析失败: ${result.error || result.message}`)
      }
    } catch (error) {
      logError(`请求错误: ${error.message}`)
    }
    
    // 添加延迟避免请求过快
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}

// 测试任务分解接口
async function testDecomposeTask() {
  logHeader('测试任务分解接口 (decompose)')
  
  for (let i = 0; i < TEST_DATA.decomposeTask.length; i++) {
    const { title, description } = TEST_DATA.decomposeTask[i]
    logInfo(`测试用例 ${i + 1}: "${title}"`)
    
    try {
      const result = await apiRequest('/ai/decompose', {
        method: 'POST',
        body: JSON.stringify({ title, description })
      })
      
      if (result.success) {
        logSuccess(`分解成功: ${result.message}`)
        if (result.subtasks && result.subtasks.length > 0) {
          log(`   - 生成了 ${result.subtasks.length} 个子任务:`)
          result.subtasks.forEach((subtask, index) => {
            log(`     ${index + 1}. ${subtask.title} (${subtask.estimatedTime})`)
          })
        }
        if (result.analysis) {
          log(`   - 分析: ${result.analysis}`)
        }
      } else {
        logWarning(`分解失败: ${result.error || result.message}`)
      }
    } catch (error) {
      logError(`请求错误: ${error.message}`)
    }
    
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}

// 测试智能搜索接口
async function testSearch() {
  logHeader('测试智能搜索接口 (search)')
  
  for (let i = 0; i < TEST_DATA.search.length; i++) {
    const query = TEST_DATA.search[i]
    logInfo(`测试用例 ${i + 1}: "${query}"`)
    
    try {
      const result = await apiRequest('/ai/search', {
        method: 'POST',
        body: JSON.stringify({ query })
      })
      
      if (result.success) {
        logSuccess(`搜索成功: ${result.message}`)
        if (result.intent) {
          log(`   - 搜索意图: ${result.intent}`)
        }
        if (result.searchType) {
          log(`   - 搜索类型: ${result.searchType}`)
        }
        if (result.suggestions && result.suggestions.length > 0) {
          log(`   - 相关建议: ${result.suggestions.join(', ')}`)
        }
        if (result.searchTips && result.searchTips.length > 0) {
          log(`   - 搜索技巧: ${result.searchTips.join(', ')}`)
        }
      } else {
        logWarning(`搜索失败: ${result.error || result.message}`)
      }
    } catch (error) {
      logError(`请求错误: ${error.message}`)
    }
    
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}

// 测试获取建议接口
async function testGetSuggestions() {
  logHeader('测试获取建议接口 (suggestions)')
  
  try {
    const result = await apiRequest('/ai/suggestions', {
      method: 'GET'
    })
    
    if (result.success) {
      logSuccess(`获取建议成功: ${result.message}`)
      if (result.suggestions && result.suggestions.length > 0) {
        log(`   - 生成了 ${result.suggestions.length} 条建议:`)
        result.suggestions.forEach((suggestion, index) => {
          log(`     ${index + 1}. [${suggestion.type}] ${suggestion.message}`)
          if (suggestion.actions && suggestion.actions.length > 0) {
            const actions = suggestion.actions.map(a => a.label).join(', ')
            log(`       操作: ${actions}`)
          }
        })
      } else {
        logWarning('没有生成任何建议')
      }
    } else {
      logWarning(`获取建议失败: ${result.error || result.message}`)
    }
  } catch (error) {
    logError(`请求错误: ${error.message}`)
  }
}

// 测试个性化建议接口
async function testPersonalizedSuggestions() {
  logHeader('测试个性化建议接口 (personalized-suggestions)')
  
  for (let i = 0; i < TEST_DATA.personalizedSuggestions.length; i++) {
    const { userId, context } = TEST_DATA.personalizedSuggestions[i]
    logInfo(`测试用例 ${i + 1}: 用户 ${userId}, 上下文 "${context}"`)
    
    try {
      const result = await apiRequest('/ai/personalized-suggestions', {
        method: 'POST',
        body: JSON.stringify({ userId, context })
      })
      
      if (result.success) {
        logSuccess(`获取个性化建议成功: ${result.message}`)
        if (result.suggestions && result.suggestions.length > 0) {
          log(`   - 生成了 ${result.suggestions.length} 条个性化建议:`)
          result.suggestions.forEach((suggestion, index) => {
            log(`     ${index + 1}. [${suggestion.type}] ${suggestion.message}`)
            if (suggestion.reasoning) {
              log(`        理由: ${suggestion.reasoning}`)
            }
            if (suggestion.actions && suggestion.actions.length > 0) {
              const actions = suggestion.actions.map(a => a.label).join(', ')
              log(`        操作: ${actions}`)
            }
          })
        } else {
          logWarning('没有生成任何个性化建议')
        }
      } else {
        logWarning(`获取个性化建议失败: ${result.error || result.message}`)
      }
    } catch (error) {
      logError(`请求错误: ${error.message}`)
    }
    
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}

// 测试健康检查接口
async function testHealthCheck() {
  logHeader('测试健康检查接口 (health)')
  
  try {
    const result = await apiRequest('/health', {
      method: 'GET'
    })
    
    if (result.status === 'ok') {
      logSuccess('健康检查通过')
      if (result.timestamp) {
        log(`   - 时间戳: ${result.timestamp}`)
      }
      if (result.uptime) {
        log(`   - 运行时间: ${result.uptime}`)
      }
    } else {
      logWarning(`健康检查异常: ${JSON.stringify(result)}`)
    }
  } catch (error) {
    logError(`健康检查失败: ${error.message}`)
  }
}

// 性能测试
async function performanceTest() {
  logHeader('性能测试')
  
  const testCases = [
    { name: '智能解析', endpoint: '/ai/smart-parse', data: { text: '明天上午9点开会' } },
    { name: '任务分解', endpoint: '/ai/decompose', data: { title: '完成项目报告', description: '整理数据并撰写报告' } },
    { name: '智能搜索', endpoint: '/ai/search', data: { query: '高优先级' } }
  ]
  
  for (const testCase of testCases) {
    logInfo(`测试 ${testCase.name} 接口性能...`)
    
    const times = []
    const iterations = 3
    
    for (let i = 0; i < iterations; i++) {
      const startTime = Date.now()
      
      try {
        await apiRequest(testCase.endpoint, {
          method: 'POST',
          body: JSON.stringify(testCase.data)
        })
        
        const endTime = Date.now()
        const duration = endTime - startTime
        times.push(duration)
        
        log(`   第 ${i + 1} 次: ${duration}ms`)
      } catch (error) {
        logError(`   第 ${i + 1} 次失败: ${error.message}`)
      }
      
      await new Promise(resolve => setTimeout(resolve, 500))
    }
    
    if (times.length > 0) {
      const avgTime = times.reduce((a, b) => a + b, 0) / times.length
      const minTime = Math.min(...times)
      const maxTime = Math.max(...times)
      
      logSuccess(`${testCase.name} 性能统计:`)
      log(`   - 平均响应时间: ${avgTime.toFixed(2)}ms`)
      log(`   - 最快响应时间: ${minTime}ms`)
      log(`   - 最慢响应时间: ${maxTime}ms`)
    }
  }
}

// 主测试函数
async function runAllTests() {
  logHeader('开始全面AI接口测试')
  logInfo(`测试目标: ${API_BASE_URL}`)
  logInfo(`测试用户ID: ${TEST_CONFIG.userId}`)
  logInfo(`超时设置: ${TEST_CONFIG.timeout}ms`)
  
  const startTime = Date.now()
  
  try {
    // 基础功能测试
    await testHealthCheck()
    await testSmartParse()
    await testDecomposeTask()
    await testSearch()
    await testGetSuggestions()
    await testPersonalizedSuggestions()
    
    // 性能测试
    await performanceTest()
    
    const totalTime = Date.now() - startTime
    logHeader('测试完成')
    logSuccess(`总测试时间: ${totalTime}ms`)
    logSuccess('所有测试用例执行完毕！')
    
  } catch (error) {
    logError(`测试过程中发生错误: ${error.message}`)
    process.exit(1)
  }
}

// 错误处理
process.on('unhandledRejection', (reason, promise) => {
  logError('未处理的Promise拒绝:')
  logError(`原因: ${reason}`)
  logError(`Promise: ${promise}`)
  process.exit(1)
})

process.on('uncaughtException', (error) => {
  logError('未捕获的异常:')
  logError(`错误: ${error.message}`)
  logError(`堆栈: ${error.stack}`)
  process.exit(1)
})

// 运行测试
if (require.main === module) {
  runAllTests().catch(error => {
    logError(`测试执行失败: ${error.message}`)
    process.exit(1)
  })
}

module.exports = {
  runAllTests,
  testSmartParse,
  testDecomposeTask,
  testSearch,
  testGetSuggestions,
  testPersonalizedSuggestions,
  testHealthCheck,
  performanceTest
}
